package com.tim.helper.inactive.jmeter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Adminis
 * @date 2020年8月11日
 * DESC: 
 */
@Slf4j
public class GenJmeterArgs {
	/**
	 * 根据浏览器记录，生成jmeter参数
	 * 	输出为csv格式
	 * @author Litianlin
	 * @throws IOException 
	 * @date 2020年8月11日
	 */
	@Test
	public void genJmeterArgs() throws IOException {
		String path = "workResponsibility";
		genArgs(path);
		
	}

	public List<String> genArgs(String path) throws IOException {
		String dir = "C:/Users/Adminis/Desktop/start/req/";
		String file = dir+path+".csv";
		StringBuilder builder = new StringBuilder();
		
		Files.readAllLines(Paths.get(dir, path+".har"))
			.stream()
			.forEach(builder::append);
		JSONObject jObj = JSON.parseObject(builder.toString());
		JSONArray jArr = jObj.getJSONObject("log").getJSONArray("entries");
		List<String> content = new ArrayList<>(128);
		content.add("url,queryArg,body,query");
		for (int i = 0; i < jArr.size(); i++) {
			JSONObject json = (JSONObject) jArr.get(i);
			JSONObject request = json.getJSONObject("request");
			String url = request.getString("url");
			url = handleUrl(url);
			if(url==null) {
				continue;
			}
			StringBuilder sb = new StringBuilder(toCsvFormat(url));
			JSONArray queryArgs = request.getJSONArray("queryString");
			StringBuilder args = new StringBuilder();
			if(ObjectUtil.isNotEmpty(queryArgs)) {
				for (int j = 0; j < queryArgs.size(); j++) {
					JSONObject arg = (JSONObject) queryArgs.get(j);
					args.append(arg.getString("name"));
					String value = arg.getString("value");
					if(StringUtils.hasLength(value)) {
						args.append("=").append(value);
					}
					args.append("&");
				}
			}
			sb.append(",").append(toCsvFormat(args.toString()));
			JSONObject postData = request.getJSONObject("postData");
			String text = postData!=null ? postData.getString("text") : "";
//			if(StringUtils.hasText(text)) {
//				if(!JSON.isValid(text)) {
//					//非json，转为json。pageNum=1&pageSize=22格式
//					text = text.trim();
//					text = text.endsWith("&") ? text.substring(0, text.length()) : text;
//					text = text.replaceAll("=", "\":\"")
//							.replaceAll("&", "\",\"");
//					text = "{\""+text+"\"}";					
//				}
//			}
			sb.append(",").append(toCsvFormat(text));
			String queryString = request.getString("queryString");
			queryString = "[]".equals(queryString) ? "" : queryString;
			sb.append(",").append(toCsvFormat(queryString));//csv特殊格式
			content.add(sb.toString());
		}
		Files.write(Paths.get(file), content);
		return content;
	}
	
	private String handleUrl(String url) {
		if(!StringUtils.hasText(url)) {
			return null;
		}
		url = url.substring(url.indexOf(':')+3);//去除协议部分
		int idx = url.indexOf('/');//去除端口
		url = idx>0 ? url.substring(idx) : url;
		if(url.contains(".")) {
			System.out.println(url);
			return null;//资源类返回null
		}
		idx = url.indexOf('?');//请求参数
		return idx>-1 ? url.substring(0, idx) : url;
	}
	
	private String toCsvFormat(String str) {
		str = str.replaceAll("\"", "\"\"");
		return new StringBuilder("\"").append(str).append("\"").toString();
	}
	
	/**
	 * 构建jmter body参数
	 * 
	 * @author Litianlin
	 * @date 2020年8月27日
	 */
	String template = "\t\"%1$s\": \"\",";
	String lastTemplate = "\t\"%1$s\": \"\"";
	@Test
	public void jmeterBodyArg() {
//		Class<?> clz = AttendanceAccountBindDTO.class;
//		List<Field> fieldList = getFields(clz);
//		List<String> list = new ArrayList<>();
//		list.add("{");
//		fieldList.subList(0, fieldList.size()-1).forEach(field->list.add(String.format(template, field.getName())));
//		list.add(String.format(lastTemplate, fieldList.get(fieldList.size()-1).getName()));
//		list.add("}");
//		list.forEach(System.out::println);
	}
	
	@Test
	public void jmeterQueryArg() {
//		Class<?> clz = QueryAppVersionDTO.class;
//		List<Field> fieldList = getFields(clz);
//		fieldList.stream()
//			.map(field->field.getName()+"=&")
//			.forEach(System.out::print);
	}
	public static List<Field> getFields(Class<?> clz){
		List<Field> list = new ArrayList<>();
		do {
			Field[] flds = clz.getDeclaredFields();
			for (int i = 0; i < flds.length; i++) {
				Field field = flds[i];
				//判定是否静态变量。变量声明，类型前字段为修饰符。
				if(!Modifier.isStatic(field.getModifiers())){
//					System.out.println(String.format(template, field.getName()));
//					ApiModelProperty anno = field.getAnnotation(ApiModelProperty.class);
//					if(anno!=null && anno.hidden()) {
//						continue;//排除隐藏
//					}
//					list.add(field);
				}
			}
			clz = clz.getSuperclass();
		}while(clz!=null);
		return list;
	}
	@Test
	public void jsonValidate() {
		String text ="pageNum=1&pageSize=24&receive=&taskStatus=&isFinish=&executor=&publicId=&queryType=3&remark=";
		String[] strs = text.split("[=&]");
		System.out.println(strs.length);
		System.out.println(JSON.isValid(text));
		text = text.trim();
		text = text.endsWith("&") ? text.substring(0, text.length()) : text;
		text = text.replaceAll("=", "\":\"")
				.replaceAll("&", "\",\"");
		text = "{\""+text+"\"}";
		System.out.println(JSON.isValid(text));
		//		System.out.println(JSONValidator.from(text).validate());
		text ="{\"progressStatus\":\"1\",\"progressContent\":\"3\",\"pictrue\":\"\",\"taskId\":\"291\"}";
		System.out.println(JSONValidator.from(text).validate());
	}
}
